from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from cart.models import Cart
from cart.serializers import CartSerializers
from utils.permission import auto_user, update_auto_user, destroy_auto_user


class CartViewSet(ModelViewSet):
    serializer_class = CartSerializers
    permission_classes = [IsAuthenticated]
    #购物车要重写queryset，因为不能查询所有的购物车信息，只能查询属于哪一个用户的购物车数据

    #通过访问的用户数据去查询关联的购物车数据，然后返回这样子购物车就是本来这个用户的购物车数据了
    def get_queryset(self):
        return self.request.user.cart_set.filter(is_delete=False)

    @auto_user
    def create(self, request, *args, **kwargs):
        try:
            self.get_queryset().get(commodity=request.data['commodity'])  # 判断商品是否存在于购物车当中
        except:
            ModelViewSet.create(self, request, *args, **kwargs)
            return Response({
                'status': status.HTTP_201_CREATED,
                'msg': '商品成功添加至购物车'
            })
        return Response({
            'status': status.HTTP_204_NO_CONTENT,
            'msg': '商品已存在购物车当中'
        })


    @update_auto_user
    def update(self, request, *args, **kwargs):
        return ModelViewSet.update(self, request, *args, **kwargs)


    @destroy_auto_user
    def destroy(self, request, *args, **kwargs):
        self.get_queryset().update(is_delete=False)
        ModelViewSet.destroy(self, request, *args, **kwargs)  # 删除前端传过来的数据
        serializer = self.get_serializer(self.get_queryset(), many=True)  # 重新查询数据，并返回前端
        return Response(serializer.data)
    @action(methods=['put'],detail=True)
    def update_cart_num(self,request,pk):
        print(pk)
        print(request.data)
        try:
            data = self.get_queryset().get(id=pk)
        except:
            return Response({
                'status':status.HTTP_404_NOT_FOUND,
                'msg':'没有这个数据'
            })
        if int(request.data['num'])>data.commodity.stock:
            return Response({
                'status':status.HTTP_401_UNAUTHORIZED,
                'msg':'购买的商品超过库存量'
            })
        else:
            Cart.objects.filter(id=pk).update(number=request.data['num'])
            return Response({
                'status':status.HTTP_202_ACCEPTED
            })
    @action(methods=['get'],detail=False)
    def get_check_cartdatav(self,request):
        good_data = []
        price_all = 0
        num_all = 0
        #request.query_params是接收到，url路由最后的？后面的数据
        #enumerate是解构数据的意思
        for item,index in enumerate(request.query_params):
            try:
                data = self.get_queryset().get(id = request.query_params[str(item)])
            except data.DoesNotExist:
                return Response(status.HTTP_404_NOT_FOUND)
            serializer = self.get_serializer(data)#转序列化
            num = Cart.objects.get(id = request.query_params[str(item)]).number
            num_all += num
            #价格通过序列化器的数据拿到
            price = eval(serializer.data['commodityDetail']['price'])*num
            price_all += price
            good_data.append(serializer.data)
        data = {
            'good_datas': good_data,
            'price': '%.2f' % price_all,
            'num': num_all,
        }
        return Response(data)







